import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import {
	ListTranslator,
	RxMainInjectDataSourceEntity,
	PollParamsEntity,
	SelectOption,
	PollTerModel,
	PollCometd,
} from './translator'
import { differenceBy } from 'lodash-es'
import { fetchChangePollInfo } from '@/api/manager/poll'
import Alert from '@/components/Alert'
import { useMccStore } from '../../store'
import { Mt, MtEntity } from '@/api/manager/mt'
import { useManagerStore } from '../main/manager/store'
import { PollEntity } from '@/api/manager/poll/interface'

type StateStore = {
	/**预案列表 */
	planOptions: SelectOption[]
	/**预案选中的值 */
	planValue: string
	/**预案名称 */
	preName: string
	/**轮询状态0 空闲  1轮询中  2暂停*/
	state: 0 | 1 | 2
	/**轮询终端的位置*/
	poll_index: number
	/**当前轮询到的终端*/
	cur_poll_mt: MtEntity | null
	/**显示的轮询终端 */
	list: Array<PollTerModel>
	/**轮询间隔 */
	keep_time: number | undefined
	/**轮询次数 */
	num?: number
	/**不限次数勾选框 */
	unlimited: boolean
	/**保存预案的模态框 */
	isSavePlanOpen: boolean
	/**表示当前的轮询类型  1 会议轮询    2 管理方轮询   3 上传轮询*/
	poll_mode: 1 | 2 | 3
	/**表示当前的轮询类型  1 会议轮询    2 管理方轮询   3 上传轮询 对应轮询类型*/
	poll_mode_text: string
	/**是否是上传轮询 */
	is_upload: boolean
	/**轮询间隔下拉列表 */
	pollIntervalOptions: SelectOption[]
	/**轮询间隔选择值 */
	pollIntervalOptionsVal: string
	/**输入的预案名称 */
	name: string
	/**消息推送使用的数据 */
	previewData: any
	/**是否处于编辑状态*/
	isEdit: boolean
	/**当前的轮询模式*/
	mode: number | null
	/**会议轮询消息推送*/
	ws_mcc_meeting_poll: PollCometd | null
	/**上传轮询*/
	ws_mcc_meeting_up_poll: PollCometd | null
	/**
	 *  当前轮询的终端，
	 */
	activePollingMts: {
		mtKey: string
		isActive: boolean
	}[]
	_start: string
	_changes: string[]
}
type PollStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	addList: (_list: MtEntity[]) => void
	removeMt: (mtKeys: string[]) => void
	updateList: (updateList: MtEntity[]) => void
	toggleClick: (mtKey: string) => void
	toggleCtrl: (mtKey: string) => void
	toggleShift: (mtKey: string) => void
	/**主要就是在会议轮询下更新左侧图标 */
	getCurList: () => void
	/**获取查询参数*/
	getPara: () => PollParamsEntity
	/**获取查询参数*/
	checkPara: (flag?: boolean) => boolean
	/**保存轮询数据*/
	saveStartList: (flag?: boolean) => void
	/**上传轮询检测管理方 */
	hasChairman: () => boolean
	/**推送数据*/
	mcc_meeting_poll: (data: PollCometd) => void
	/**推送数据(上传轮询)*/
	mcc_meeting_uppoll: (data: PollCometd) => void
	/**获取保存和更新预案数据 */
	getPlanPara: (flag: boolean) => any
	handleUpTop: () => void
	handleUp: () => void
	handleDown: () => void
	handleDownBottom: () => void
}
const initialState: StateStore = {
	planOptions: [{ label: t('不使用预案'), value: '0' }],
	is_upload: false,
	isEdit: false,
	planValue: '',
	// type: 1,
	num: 0,
	state: 1,
	// pollPos: 0,
	cur_poll_mt: null,
	poll_index: 1,
	list: [],
	preName: '',
	isSavePlanOpen: false,
	poll_mode: 1,
	poll_mode_text: t('会议轮询'),
	// isUpload: false,
	unlimited: false,
	keep_time: 30,
	mode: 1,
	pollIntervalOptions: [
		{ label: t('15(快)'), value: '15' },
		{ label: t('30(中)'), value: '30' },
		{ label: t('60(慢)'), value: '60' },
		{ label: t('自定义'), value: '0' },
	],
	pollIntervalOptionsVal: '30',
	name: '',
	previewData: {},
	activePollingMts: [],
	ws_mcc_meeting_poll: null,
	ws_mcc_meeting_up_poll: null,
	_start: '',
	_changes: [],
}
export const store = createVanilla<PollStore>((set, get) => ({
	...initialState,
	update: (d) => set({ ...d }),
	reset: () => set(initialState),
	/**获取当前的终端列表*/
	getCurList: () => {
		/**如果不是会议轮询*/
		if (useMccStore.getState().curPage !== 'meeting_poll') {
			// if (window.TS.mcc.nowPage !== 'mcc_meeting_pollparam') {
			return
		}
		const list = get().list
		const curPollMt = get().cur_poll_mt
		let curList: RxMainInjectDataSourceEntity = list.map((item) => {
			return {
				mtKey: item.mtKey || '',
				isActive: curPollMt ? (item.mtKey === curPollMt.mt_key ? true : false) : false,
			}
		})
		set({ activePollingMts: curList })
		// rxMain.setIsOpenMeetingPoll(true)
	},
	/**获取轮询参数*/
	getPara: () => {
		/**轮询终端*/
		const { list, poll_mode, unlimited, preName, name, num, keep_time, planValue, mode } = get()
		const _preName = planValue === '' ? '' : preName
		let _mode = poll_mode === 1 || poll_mode === 2 ? mode : null
		let pollMt = list.map((item) => {
			const data = item.mcc
			return {
				account_type: Number(data.accountType ? data.accountType : 0),
				mt_id: data.mtid ? data.mtid : '',
				account: data.account ? data.account : '',
				mt_key: data.mtKey ? data.mtKey : '',
				moid: data.moid ? data.moid : '',
				e164: data.e164 ? data.e164 : '',
				conf_e164: data.confE164 ? data.confE164 : '',
				stream: data.status.isStream ? 1 : 0,
			}
		})
		/**获取位置*/
		let max = 0
		let checkedList = list.filter((item, index) => {
			if (item.status.checked) {
				max = index
			}
			return item.status.checked
		})
		let _pollpos = checkedList.length !== 1 ? 1 : max + 1
		var data: PollParamsEntity = {
			id: '',
			name: _preName || '' /**预案名称 */,
			num: unlimited ? 0 : num || 0, //轮询次数
			keep_time: keep_time ?? 0,
			mode: _mode,
			members: pollMt /**轮询成员 */,
			poll_index: _pollpos /**新加入指定位置 */,
		}
		return data
	},
	/**
	 *
	 * @param isUpdate 是否是更新预案
	 * @returns
	 */
	getPlanPara: (isUpdate: boolean) => {
		const { list, poll_mode, preName, name, num, keep_time, planValue, mode } = get()
		const _members = list.map((item) => {
			const data = item.mcc
			return {
				account_type: Number(data.accountType ? data.accountType : 0),
				mt_id: data.mtid ? data.mtid : '',
				account: data.account ? data.account : '',
				mt_key: data.mtKey ? data.mtKey : '',
				moid: data.moid ? data.moid : '',
				e164: data.e164 ? data.e164 : '',
				conf_e164: data.confE164 ? data.confE164 : '',
			}
		})
		const _name = isUpdate ? preName : name
		const _id = isUpdate ? planValue : ''
		/**获取模式*/
		let _mode = poll_mode === 1 || poll_mode === 2 ? mode : null
		return {
			mode: _mode,
			id: _id,
			keep_time: Number(keep_time) || 30, //轮询间隔时间（秒
			members: _members, //轮询成员
			name: _name, // 预案名称
			num: Number(num) || 0, //轮询次数，0无限次轮询
		}
	},
	/**检测预案数据 */
	checkPara: (flag?: boolean) => {
		const { getPara, poll_mode, unlimited } = get()
		const { members: list, keep_time, num } = getPara()
		if (!flag && list.length === 0) {
			Alert(t('至少选择一个与会方参加轮询'))
			return false
		}
		if (list.length > 5000) {
			Alert(t('参与轮询与会方最多为5000方'))
			return false
		}
		if (!unlimited) {
			if (num < 1 || num > 9999) {
				Alert(t('自定义轮询次数范围为1~9999'))
				return false
			}
		}
		if (!keep_time) {
			Alert(t('请设置轮询间隔'))
			return false
		} else {
			if (keep_time > 7200 || keep_time < 5) {
				Alert(t('自定义间隔时间范围为5~7200'))
				return false
			}
		}
		/**管理方轮询*/
		const chairman_flag = get().hasChairman()
		if (poll_mode === 2 && !flag && !chairman_flag) {
			Alert(t('请先指定管理方，再开启管理方轮询'))
			return false
		}
		if (poll_mode === 2 && !flag) {
			/**获取管理方 */
			const chairman = useManagerStore.getState().chairman
			let is_success = list.findIndex((item) => {
				return item.mt_key === chairman?.mtKey
			})
			if (is_success !== -1) {
				Alert(t('请从管理方列表中删除当前管理方，方可开启管理方轮询'))
				return false
			}
		}
		return true
	},
	/**管理方轮询时必须要有管理方并且管理方在线*/
	hasChairman: () => {
		//管理方轮询时必须要有管理方；
		const chairman = useManagerStore.getState().chairman
		if (!chairman) return false
		if (!chairman.mtKey) return false
		if (!chairman.status.isOnline) return false
		return true
	},
	/**保存开始轮询数据*/
	saveStartList: async (flag?: boolean) => {
		const params = get().getPara()
		const list = get().list
		const state = get().state
		const type = get().poll_mode
		const cur_poll_mt = get().cur_poll_mt
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		if (Number(state) === 0) {
			//只有在正在轮询时才会保存列表
			return
		}
		const poll_index = list.findIndex((item, index) => {
			return item.mtKey === cur_poll_mt?.mt_key
		})
		params.poll_index = poll_index === -1 ? 1 : poll_index + 1
		if (flag) {
			let max = 0
			let checkedList = list.filter((item, index) => {
				if (item.status.checked) {
					max = index
				}
				return item.status.checked
			})
			let _pollpos = checkedList.length !== 1 ? 1 : max + 1
			params.poll_index = _pollpos
		}
		const res = await fetchChangePollInfo(meetingMoid, type, params)
		!res.success && Alert(res.description || t('操作失败'))
	},
	/**新增终端*/
	addList: (addList) => {
		const { poll_mode, list } = get()
		let _updates: Array<MtEntity> = []
		if (poll_mode === 1) {
			/**上传轮询*/
			_updates = addList
		}
		if (poll_mode === 2) {
			/**管理方轮询 */
			_updates = addList.filter((x) => x.chairman !== 1)
			if (addList.length > _updates.length) {
				Alert(t('管理方不能加入管理方轮询列表'))
			}
		}
		if (poll_mode === 3) {
			/**上传轮询*/
			_updates = addList.filter((mt) => mt.conf_level === 2)
		}
		let mts = ListTranslator(_updates)
		const insertList = differenceBy(mts, list, (x) => x.mtKey)
		set({ list: [...list, ...insertList] })
	},
	/**移除终端*/
	removeMt: (mtKeys) => {
		const list = get().list
		const poll_mode = get().poll_mode
		const unRemove = list.filter((l) => !mtKeys.includes(l.mtKey))
		set({ list: unRemove })
		poll_mode === 1 && get().getCurList()
	},
	/**更新终端*/
	updateList: (updateList = []) => {
		let _updates = updateList
		const newList = get().list
		for (const mt of _updates) {
			for (const item of newList) {
				if (item.mtKey === mt.mt_key) {
					item.mcc = new Mt(mt)
				}
			}
		}
		set({ list: [...newList] })
	},
	toggleClick: (mtKey) => {
		const list = get().list
		list.forEach((item) => {
			if (item.mtKey === mtKey) {
				item.status.checked = true
			} else {
				item.status.checked = false
			}
		})
		set({ list: [...list], _start: mtKey, _changes: [] })
	},
	toggleCtrl: (mtKey) => {
		const list = get().list
		list.forEach((item) => {
			if (item.mtKey === mtKey) {
				item.status.checked = !item.status.checked
			}
		})
		set({ list: [...list], _start: mtKey, _changes: [] })
	},
	toggleShift: (mtKey) => {
		const { list, _changes, _start } = get()
		if (_changes.length > 0) {
			for (const item of list) {
				if (_changes.includes(item.mtKey)) {
					item.status.checked = false
				}
			}
		}
		let newChanges = []
		let startItem = list.find((x) => x.mtKey === _start)
		if (startItem) {
			if (startItem?.mtKey === mtKey) {
				startItem.status.checked = true
				newChanges.push(startItem?.mtKey)
			} else {
				let _flag = false,
					_time = 0
				for (const item of list) {
					if (item.mtKey === mtKey || item.mtKey === _start) {
						item.status.checked = true
						newChanges.push(item.mtKey)
						_flag = ++_time === 1
					}
					if (_flag) {
						item.status.checked = true
						newChanges.push(item.mtKey)
					}
				}
			}
		}
		set({ list: [...list], _changes: newChanges })
	},
	mcc_meeting_poll: (data) => {
		set({ ws_mcc_meeting_poll: data })
	},
	mcc_meeting_uppoll: (data) => {
		set({ ws_mcc_meeting_up_poll: data })
	},
	handleUpTop: () => {
		const { list, saveStartList } = get()
		let checkedList = list.filter((x) => x.status.checked)
		const unCheckedList = list.filter((x) => !x.status.checked)
		set({ list: [...checkedList, ...unCheckedList] })
		saveStartList()
	},
	handleUp: () => {
		const { list, handleUpTop, saveStartList } = get()
		const min = list.findIndex((x) => x.status.checked)
		if (min === 0 || min === 1) {
			handleUpTop()
			return
		}
		let checkedList = list.filter((x) => x.status.checked)
		const unCheckedList = list.filter((x) => !x.status.checked)
		set({
			list: [
				...unCheckedList.slice(0, min - 1),
				...checkedList,
				...unCheckedList.slice(min - 1, unCheckedList.length),
			],
		})
		saveStartList()
	},
	handleDown: () => {
		const { list, handleDownBottom, saveStartList } = get()
		let max = 0
		list.forEach((x, index) => {
			if (x.status.checked) {
				max = index
			}
		})
		if (max === list.length - 2 || max === list.length - 1) {
			handleDownBottom()
			return
		}
		let checkedList = list.filter((x) => x.status.checked)
		const unCheckedList = list.filter((x) => !x.status.checked)
		set({
			list: [
				...unCheckedList.slice(0, max + 1),
				...checkedList,
				...unCheckedList.slice(max + 1, unCheckedList.length),
			],
		})
		saveStartList()
	},
	handleDownBottom: () => {
		const { list, saveStartList } = get()
		let checkedList = list.filter((x) => x.status.checked)
		const unCheckedList = list.filter((x) => !x.status.checked)
		set({ list: [...unCheckedList, ...checkedList] })
		saveStartList()
	},
}))
export const usePollStore = create(store)
